package com.mrx.commons.mail;

import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import org.springframework.util.Assert;

import java.util.Collections;
import java.util.Objects;
import java.util.Properties;

/**
 * @author Mr.X
 * @since 2024-01-12 14:43
 **/
public class XEnvPropertySourceFactory implements PropertySourceFactory {

    private static final Logger logger = LoggerFactory.getLogger(XEnvPropertySourceFactory.class);

    @NotNull
    @Override
    public PropertySource<?> createPropertySource(String name, @NotNull EncodedResource encodedResource) {
        Resource resource = encodedResource.getResource();
        if (!resource.exists()) {
            logger.info("找不到文件: {}", resource.getFilename());
            return new MapPropertySource(name, Collections.emptyMap());
        }
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource);
        Properties properties = factory.getObject();
        Assert.notNull(properties, "Properties cannot be null");
        return new PropertiesPropertySource(Objects.requireNonNull(resource.getFilename()), properties);
    }

}
